<template>
  <div class="chapter-container">
    <header class="chapter-title">
      <n-button text @click="toList">
        <template #icon>
          <n-icon size="22"><ArrowBack /></n-icon>
        </template>
        <template #default>
          <span class="font-16"> 返回 </span>
        </template>
      </n-button>
    </header>
    <div class="video-section">
      <!-- 视频头部信息 -->
      <div class="video-header">
        <h1 class="course-title">{{ chapterInfo.title }}</h1>
        <div class="video-meta">
          <div class="meta-item">
            <i class="fas fa-play-circle"></i>
            <span>{{ chapterInfo.viewCount || 0 }}次播放</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-comment-alt"></i>
            <span>{{ chapterInfo.commentCount }}条评论</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-clock"></i>
            <span>{{
              chapterInfo.createTime ? formatToDate(new Date(chapterInfo.createTime)) : ''
            }}</span>
          </div>
        </div>
      </div>

      <!-- 视频播放区域 -->
      <div class="video-container">
        <video-play :chapter-row="props.chapterRow" style="height: 600px" />
        <!--        <div class="video-overlay">-->
        <!--          <div class="play-icon">-->
        <!--            <i class="fas fa-play"></i>-->
        <!--          </div>-->
        <!--          <div class="video-title">人工智能： 组件化设计思想与实战</div>-->
        <!--        </div>-->
      </div>

      <!-- 互动按钮区域 -->
      <!--    <div class="video-actions">-->
      <!--      <button class="action-btn" :class="{ liked: isLiked, active: isLiked }" @click="toggleLike">-->
      <!--        <i class="fas" :class="isLiked ? 'fa-heart' : 'fa-heart'"></i>-->
      <!--        <span>{{ isLiked ? '已点赞' : '点赞' }}</span>-->
      <!--        &lt;!&ndash;        <span>{{ chapterInfo.likeCount }}</span>&ndash;&gt;-->
      <!--      </button>-->

      <!--      <button class="action-btn">-->
      <!--        <i class="fas fa-share-alt"></i>-->
      <!--        <span>分享</span>-->
      <!--      </button>-->

      <!--      <button-->
      <!--        class="action-btn userCenter-btn"-->
      <!--        :class="{ active: isSubscribed }"-->
      <!--        @click="toggleSubscribe"-->
      <!--      >-->
      <!--        <i class="fas" :class="isSubscribed ? 'fa-bell' : 'fa-bell'"></i>-->
      <!--        <span>{{ isSubscribed ? '已订阅' : '订阅课程' }}</span>-->
      <!--      </button>-->
      <!--    </div>-->

      <!-- 相关标签 -->
      <!--    <div class="related-tags">-->
      <!--      <h3 class="tags-title">相关标签</h3>-->
      <!--      <div class="tags-container">-->
      <!--        <div v-for="tag in course.tags" :key="tag" class="tag">{{ tag }}</div>-->
      <!--      </div>-->
      <!--    </div>-->

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3 class="section-title">
          <span>评论 ({{ chapterInfo.commentCount }})</span>
        </h3>

        <!-- 评论输入框 -->
        <div class="comment-input-area">
          <n-input
            class="comment-input"
            v-model:value="newComment"
            placeholder="写下你的评论..."
            maxlength="100"
          >
            <template #suffix>
              <n-button @click="addComment" tertiary circle type="primary">
                <template #icon>
                  <n-icon><IosSend /></n-icon>
                </template>
              </n-button>
            </template>
          </n-input>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div class="comment-item" v-for="comment in comments" :key="comment.id">
            <n-avatar class="avatar" :src="comment?.user?.avatar" round />
            <!--          <div class="avatar">-->
            <!--            {{ comment.author.charAt(0) }}-->
            <!--          </div>-->
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment?.user?.username }}</span>
                <span class="badge author-badge" v-if="comment.isAuthor">作者</span>
                <span class="badge user-badge" v-if="comment.isLoginUser">我</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
              <div class="comment-actions">
                <!--              <div class="comment-action" @click="toggleCommentLike(comment)">-->
                <!--                <i class="fas fa-heart" :class="{ liked: comment.isLiked }"></i>-->
                <!--                <span>{{ comment.isLiked ? '已点赞' : '点赞' }}</span>-->
                <!--                <span>{{ comment.likeCount }}</span>-->
                <!--              </div>-->
                <!--              <div class="comment-action" @click="showReplyInput(comment)">-->
                <!--                <i class="fas fa-reply"></i>-->
                <!--                <span>回复</span>-->
                <!--              </div>-->
              </div>

              <!-- 回复输入框 -->
              <!--            <div class="reply-input-area" v-if="comment.showReply">-->
              <!--              <input-->
              <!--                type="text"-->
              <!--                class="reply-input"-->
              <!--                placeholder="写下你的回复..."-->
              <!--                v-model="comment.replyText"-->
              <!--              />-->
              <!--              <button class="send-btn" @click="addReply(comment)">发送</button>-->
              <!--            </div>-->

              <!-- 回复列表 -->
              <!--            <div class="replies-section" v-if="comment.replies.length > 0">-->
              <!--              <div class="toggle-replies" @click="toggleReplies(comment)">-->
              <!--                <i class="fas" :class="comment.expanded ? 'fa-chevron-up' : 'fa-chevron-down'"></i>-->
              <!--                <span>{{-->
              <!--                  comment.expanded ? '收起回复' : `展开回复 (${comment.replies.length})`-->
              <!--                }}</span>-->
              <!--              </div>-->

              <!--              <div class="reply-list" v-show="comment.expanded">-->
              <!--                <div class="comment-item" v-for="reply in comment.replies" :key="reply.id">-->
              <!--                  <div class="avatar">-->
              <!--                    {{ reply.author.charAt(0) }}-->
              <!--                  </div>-->
              <!--                  <div class="comment-content">-->
              <!--                    <div class="comment-header">-->
              <!--                      <span class="comment-author">{{ reply.author }}</span>-->
              <!--                      <template v-if="reply.replyTo">-->
              <!--                        <span>回复</span>-->
              <!--                        <span class="comment-author">{{ reply.replyTo }}</span>-->
              <!--                      </template>-->
              <!--                      <span class="badge author-badge" v-if="reply.isAuthor">作者</span>-->
              <!--                      <span class="badge user-badge" v-if="reply.isUser">我</span>-->
              <!--                      <span class="comment-time">{{ reply.time }}</span>-->
              <!--                    </div>-->
              <!--                    <p class="comment-text">{{ reply.content }}</p>-->
              <!--                    <div class="comment-actions">-->
              <!--                      <div class="comment-action" @click="toggleReplyLike(comment, reply)">-->
              <!--                        <i class="fas" :class="reply.isLiked ? 'fa-heart' : 'fa-heart'"></i>-->
              <!--                        <span>{{ reply.isLiked ? '已点赞' : '点赞' }}</span>-->
              <!--                        <span>{{ reply.likeCount }}</span>-->
              <!--                      </div>-->
              <!--                      <div class="comment-action" @click="showReplyInput(comment, reply)">-->
              <!--                        <i class="fas fa-reply"></i>-->
              <!--                        <span>回复</span>-->
              <!--                      </div>-->
              <!--                    </div>-->
              <!--                  </div>-->
              <!--                </div>-->
              <!--              </div>-->
              <!--            </div>-->
            </div>
          </div>

          <!-- 空状态提示 -->
          <div v-if="!comLoading && comments.length === 0" class="comment-tip"> 暂无评论 </div>

          <!-- 加载状态 -->
          <div v-if="comLoading" class="comment-tip"> 加载中... </div>

          <!-- 没有更多数据提示 -->
          <div v-if="!comLoading && isLastPage && comments.length > 0" class="comment-tip">
            暂无更多
          </div>
          <div
            v-if="!comLoading && comments.length !== 0 && !isLastPage"
            class="load-more"
            @click="loadMoreComments"
          >
            <span>点击加载更多评论</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import VideoPlay from './components/VideoPlayer.vue';
  import { getCommentListApi, addCommonApi } from '@/api/course';
  import { ArrowBack } from '@vicons/ionicons5';
  import { useMessage } from 'naive-ui';
  import { formatToDate } from '@/utils/dateUtil';
  import { IosSend } from '@vicons/ionicons4';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useUserStore } from '@/store/modules/user';

  const props = defineProps({
    chapterRow: {
      type: Object,
      default: () => null,
    },
  });

  const userStore = useUserStore();

  const message = useMessage();
  const emit = defineEmits(['back']);

  const chapterId = ref('');
  const chapterInfo = ref<any>({});

  // // 课程数据
  // const course = reactive({
  //   id: 1,
  //   title: '人工智能：从入门到精通',
  //   views: 24560,
  //   comments: 128,
  //   likeCount: 1560,
  //   uploadTime: '2023年6月15日',
  //   tags: ['AI开发', '人工智能', 'JavaScript', 'Web开发', '响应式设计'],
  //   author: {
  //     id: 101,
  //     name: 'AI开发大师',
  //     followers: 12800,
  //     courses: 15,
  //   },
  // });

  // 用户交互状态
  const isLiked = ref(false);
  const isSubscribed = ref(false);
  const isFollowing = ref(false);
  const currentChapter = ref(103);
  const newComment = ref('');

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const comLoading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);

  // 评论数据
  const comments = ref<any>([]);

  async function getCommonList(isRefresh = false) {
    if (comLoading.value || (isLastPage.value && !isRefresh)) return;

    comLoading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        bizType: 0,
        bizId: chapterId.value,
      };

      const data: any = await getCommentListApi(params);

      let list = data.records || [];
      if (isRefresh) {
        comments.value = list;
      } else {
        comments.value = [...comments.value, ...list];
      }

      pages.value = data.pages;

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      comLoading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    comments.value = [];
  }

  // 点赞功能
  const toggleLike = () => {
    isLiked.value = !isLiked.value;
    if (isLiked.value) {
      chapterInfo.value.likeCount++;
    } else {
      chapterInfo.value.likeCount--;
    }
  };

  // 订阅功能
  const toggleSubscribe = () => {
    isSubscribed.value = !isSubscribed.value;
  };

  // 关注功能
  const toggleFollow = () => {
    isFollowing.value = !isFollowing.value;
  };

  // 切换章节
  const changeChapter = (chapterId) => {
    currentChapter.value = chapterId;
  };

  // 切换视频
  const changeVideo = (videoId) => {
    alert(`切换到视频 ${videoId}`);
  };

  const addComLoading = ref(false);

  // 添加评论
  const addComment = async () => {
    if (!newComment.value.trim()) return;

    addComLoading.value = true;

    let params = {
      content: newComment.value,
      bizType: 0,
      bizId: chapterId.value,
    };

    const { code, data } = await addCommonApi(params);
    if (code == ResultEnum.SUCCESS) {
      comments.value.unshift({
        id: data,
        time: '刚刚',
        likeCount: 0,
        isLiked: false,
        isAuthor: false,
        isLoginUser: true,
        showReply: false,
        replyText: '',
        expanded: false,
        replies: [],
        user: {
          username: userStore?.info?.username,
          avatar: userStore?.info?.avatar,
        },
        ...params,
      });

      chapterInfo.value.commentCount++;
    } else {
      message.info('发表评论失败，请稍后重试！');
    }

    newComment.value = '';
  };

  // 添加回复
  const addReply = (comment, replyTo) => {
    if (!comment.replyText.trim()) return;

    const replyObj: any = {
      id: Date.now(),
      author: '当前用户',
      content: comment.replyText,
      time: '刚刚',
      likeCount: 0,
      isLiked: false,
      isAuthor: false,
      isUser: true,
    };

    if (replyTo) {
      replyObj.replyTo = replyTo.author;
    }

    comment.replies.push(replyObj);
    comment.replyText = '';
    comment.showReply = false;

    if (!comment.expanded) {
      comment.expanded = true;
    }
  };

  // 显示回复输入框
  const showReplyInput = (comment, reply) => {
    comment.showReply = true;
    if (reply) {
      comment.replyText = `@${reply.author} `;
    }
  };

  // 展开/收起回复
  const toggleReplies = (comment) => {
    comment.expanded = !comment.expanded;
  };

  // 评论点赞
  const toggleCommentLike = (comment) => {
    comment.isLiked = !comment.isLiked;
    if (comment.isLiked) {
      comment.likeCount++;
    } else {
      comment.likeCount--;
    }
  };

  // 回复点赞
  const toggleReplyLike = (comment, reply) => {
    reply.isLiked = !reply.isLiked;
    if (reply.isLiked) {
      reply.likeCount++;
    } else {
      reply.likeCount--;
    }
  };

  // 加载更多评论
  const loadMoreComments = () => {
    getCommonList();
  };

  function toList() {
    emit('back');
  }

  watch(
    () => props.chapterRow,
    async (chapterRow) => {
      if (!chapterRow.chapterId) {
        message.error('视频加载失败，请稍后重试');
        return;
      }
      const row = JSON.parse(JSON.stringify(chapterRow));
      chapterId.value = chapterRow.chapterId;
      chapterInfo.value = Object.assign({}, row, {
        courseType: chapterRow.courseType ? chapterRow.courseType.split(',').map(Number) : [],
      });
      getCommonList(true);
    },
    {
      deep: true,
      immediate: true,
    }
  );
</script>

<style lang="less" scoped>
  .chapter-container {
    height: 100%;
    overflow: auto;
  }

  .chapter-title {
  }

  .video-section {
    flex: 3;
    overflow: auto;
    padding: 20px;
  }

  .info-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  /* 视频头部信息 */
  .video-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  .course-title {
    font-size: 24px;
    margin-bottom: 12px;
    color: #2c3e50;
  }

  .video-meta {
    display: flex;
    gap: 20px;
    color: #666;
    font-size: 14px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  /* 视频播放器区域 */
  .video-container {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    height: 600px;
    //display: flex;
    //justify-content: center;
    //align-items: center;
    //background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  }

  .video-player {
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 1;
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    z-index: 2;
    background: rgba(0, 0, 0, 0.3);
  }

  .play-icon {
    font-size: 80px;
    opacity: 0.8;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 20px;
  }

  .play-icon:hover {
    transform: scale(1.1);
    opacity: 1;
  }

  .video-title {
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    max-width: 80%;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  }

  /* 互动按钮区域 */
  .video-actions {
    display: flex;
    padding: 15px 0;
    gap: 20px;
    border-bottom: 1px solid #eee;
  }

  .action-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 16px;
    color: #555;
    transition: all 0.3s ease;
    padding: 8px 15px;
    border-radius: 6px;
  }

  .action-btn:hover {
    background: #f5f7fa;
  }

  .action-btn.active {
    color: #ff4d4f;
  }

  .subscribe-btn.active {
    color: #1890ff;
    background: #e6f7ff;
  }

  .action-btn i {
    font-size: 20px;
    transition: transform 0.3s;
  }

  .action-btn.liked i {
    animation: pulse 0.5s;
  }

  .liked {
    color: #e74c3c;
    border-color: #fadbd8;
    background: #fdedec;
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.3);
    }
    100% {
      transform: scale(1);
    }
  }

  /* 标签区域 */
  .related-tags {
    margin: 25px 0;
  }

  .tags-title {
    font-size: 18px;
    margin-bottom: 15px;
    color: #2c3e50;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .tag {
    padding: 8px 15px;
    background: #e8f4fd;
    border-radius: 20px;
    color: #3498db;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .tag:hover {
    background: #d6eaf8;
    transform: translateY(-2px);
  }

  /* 评论区域 */
  .comments-section {
    margin-top: 25px;
  }

  .section-title {
    font-size: 18px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .comment-input-area {
    display: flex;
    gap: 10px;
    margin-bottom: 30px;
  }

  .comment-input {
    padding: 10px 0;
  }

  .send-btn {
    background: #1890ff;
    color: white;
    border: none;
    border-radius: 8px;
    padding: 0 25px;
    cursor: pointer;
    font-weight: 500;
    transition: background 0.3s;
  }

  .send-btn:hover {
    background: #40a9ff;
  }

  .comment-list {
    display: flex;
    flex-direction: column;
    gap: 25px;
  }

  .comment-item {
    display: flex;
    gap: 15px;
    background: #f9fbfd;
    border: 1px solid #eef2f7;
    padding: 20px;
    border-radius: 8px;
  }

  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f0f2f5;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    font-weight: bold;
    overflow: hidden;
  }

  .comment-content {
    flex: 1;
  }

  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 5px;
  }

  .comment-author {
    font-weight: 600;
    color: #2c3e50;
  }

  .badge {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 3px;
  }

  .author-badge {
    background: #fff7e6;
    color: #fa8c16;
  }

  .user-badge {
    background: #e6f7ff;
    color: #1890ff;
  }

  .comment-time {
    color: #999;
    font-size: 13px;
  }

  .comment-text {
    margin-bottom: 10px;
    line-height: 1.5;
  }

  .comment-actions {
    display: flex;
    gap: 15px;
    color: #666;
    font-size: 14px;
  }

  .comment-action {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    transition: color 0.3s;
  }

  .comment-action:hover {
    color: #1890ff;
  }

  .replies-section {
    margin-top: 15px;
    padding-left: 20px;
    border-left: 2px solid #eee;
  }

  .toggle-replies {
    display: flex;
    align-items: center;
    gap: 5px;
    color: #1890ff;
    margin-bottom: 15px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
  }

  .reply-input-area {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }

  .reply-input {
    flex: 1;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 14px;
  }

  .reply-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-top: 10px;
  }

  .comment-tip {
    text-align: center;
    height: 60px;
    line-height: 60px;
    color: #999;
    font-size: 16px;
  }

  .load-more {
    text-align: center;
    color: #1890ff;
    padding: 10px;
    cursor: pointer;
    font-weight: 500;
    margin-top: 10px;
  }

  /* 响应式设计 */
  @media (max-width: 992px) {
    .container {
      flex-direction: column;
    }

    .video-section,
    .info-section {
      width: 100%;
    }
  }
</style>
